#!/bin/bash -e

usage() {
  echo "usage: $0 EMAIL PASSWORD"
  echo
  echo 'Create the superuser account with the given email and password.'
  echo
  echo 'The instance must already be running in the background. You can '
  echo 'start it with: ./scripts/compose up -d'
}

if [[ -z "$1" || -z "$2" ]]; then
  usage
  exit 1
fi

echo_bold() {
  printf "\\033[1m%s\\033[0m\\n" "${@}"
}

source "${BASH_SOURCE%/*}/_realpath"

CMD="$(realpath "$0")"
DIR="$(dirname "${CMD}")"
FIG="${DIR}/compose"

EMAIL="$1"
PASSWORD="$2"

"${FIG}" exec api /bin/bash -c \
  'export $(grep -v "^#" config/env | xargs -d "\n"); node index.js create-superuser root '${EMAIL}' '${PASSWORD}'' \
  >/dev/null \
  || (echo 'Failed to create superuser; please ensure the instance is running and that no superuser has been created before.' && exit 1)

echo_bold "==> Success! Superuser created with email: ${EMAIL}"
echo "  - You may now login with: balena login --credentials --email ${EMAIL}"
